<template>
  <div class="detail" v-loading="loading">
    <div class="detail-header">
      <el-button class="btn-bg" @click="handleDelete" style="margin-left:0;" v-track="getBtnsTrackData('DELETE')">
        <i class="iconfont icon-delete task-icon task-font14"></i>
        {{$t('common.base.delete')}}
      </el-button>
      <div class="add-action">
        <!-- 这里未知联系人判断 后端有时候返回 未知联系人有时候返回null -->
        <template v-if="!customerName">
          <template v-if="!isTourist">
            <el-button
              v-if="allowCreateCustomer"
              type="primary"
              icon="el-icon-plus"
              @click="
                createCustomer(
                  imConversationInfo.id,
                  imConversationInfo.phoneNumber,
                  imConversationInfo.email
                )
              "
              v-track="getBtnsTrackData('CREATE_CUSTOMER')"
            >{{$t('common.base.customer')}}</el-button
            >
            <el-button
              v-if="allowCreateLinkman"
              type="primary"
              icon="el-icon-plus"
              @click="toSaveLinkmansave(imConversationInfo.phoneNumber,imConversationInfo.email)"
            >{{$t('common.base.contact')}}</el-button
            >
          </template>
        </template>
        <template v-else>
          <template v-if="!isTourist">
            <!-- 新建工单，事件，pass按钮 -->
            <NewConstructionByIM :user-detail="userDetail" from="imDetail"/>

            <!-- 关联事件 -->
            <AssociatedEvents
              @saveBizRel="saveBizRel"
              ref="AssociatedEvents"
              :conversation-id="imId"
              :biz-rel-infos="bizRelInfo"
              :cus-id="customerId"
              from="imDetail"
            />
          </template>
        </template>
        <el-button
          v-if="imConversationInfo.conversationStatus === 0"
          type="primary"
          @click="TransferToLabor"
          v-track="getBtnsTrackData('TRANSFER_TO_LABOR')"
        >{{$t('im.detail.btn1')}}</el-button
        >
        <el-button
          v-if="imConversationInfo.conversationStatus === 2"
          type="primary"
          @click="SessionForwarding"
          v-track="getBtnsTrackData('SESSION_FORWARDING')"
        >{{$t('im.detail.btn2')}}</el-button
        >
        <el-button
          v-if="imConversationInfo.conversationStatus === 2"
          @click="EndSession"
          type="danger"
          v-track="getBtnsTrackData('END_SESSION')"
        >{{$t('im.detail.btn3')}}</el-button
        >
      </div>
    </div>
    <!-- start 会话信息折叠面板 -->
    <base-collapse class="task-detail-main-content detail-main-content" :show-collapse="showCollapse" :direction.sync="collapseDirection" iframeId="imIframe">
      <template slot="left">
        <div class="im-detail chat-detail">
          <div :class="['im-title', {'other-title': collapseDirection !== 'left'}]">{{$t('im.detail.title1')}}</div>
          <div class="form-container" v-show="collapseDirection !== 'left'">
            <template>
              <div class="form-view-row">
                <label>{{$t('common.fields.imConversationNumber.displayName')}}</label>
                <div class="form-view-row-content">
                  {{ imConversationInfo.conversationNumber }}
                </div>
              </div>
            </template>
            <div class="form-view-row">
              <label>{{$t('common.fields.customerName.displayName')}}</label>
              <div
                  class="form-view-row-content customer-name"
                  @click="openCustomer(customerId)"
              >
                {{ imConversationInfo.customerName }}
                <span
                    class="iconfont icon-weixin5"
                    style="
                font-size: 10px;
                font-weight: 400;
                margin-left: 4px;
                color: #20cc62;
              "
                    v-if="isWeChat && imConversationInfo.customerName"
                ></span
                >
              </div>
            </div>
            <div class="form-view-row">
              <label>{{$t('common.fields.contact.displayName')}}</label>
              <div class="form-view-row-content">
                {{ imConversationInfo.linkmanName
                }}<span
                  class="iconfont icon-weixin5"
                  style="
                font-size: 10px;
                font-weight: 400;
                margin-left: 4px;
                color: #20cc62;
              "
                  v-if="isWeChat && imConversationInfo.linkmanName"
              ></span
              >
              </div>
            </div>
            <template>
              <div class="form-view-row">
                <label>{{$t('common.fields.imRegisterType.displayName')}}</label>
                <div class="form-view-row-content">
                  {{ registerTypeMaps[imConversationInfo.registerType]}}
                </div>
              </div>
            </template>
            <template>
              <div class="form-view-row">
                <label>{{$t('common.fields.phone.displayName')}}</label>
                <div class="form-view-row-content">
                  {{ imConversationInfo.phoneNumber }}
                </div>
              </div>
            </template>
            <!-- 纯客服云版本不显示邮箱 -->
            <template v-if="_isShowEmail">
              <div class="form-view-row">
                <label>{{$t('common.fields.email.displayName')}}</label>
                <div class="form-view-row-content">
                  {{ imConversationInfo.email }}
                </div>
              </div>
            </template>
            <template>
              <div class="form-view-row">
                <label>{{$t('common.fields.address.displayName')}}</label>
                <div class="form-view-row-content">
                  {{ imConversationInfo.address }}
                </div>
              </div>
            </template>

            <div class="form-view-row">
              <label>{{$t('common.fields.weChatNickname.displayName')}}</label>
              <div class="form-view-row-content">
                {{
                  imConversationInfo.nickname ? imConversationInfo.nickname : ''
                }}
              </div>
            </div>
            <div class="form-view-row">
              <label>{{$t('common.fields.sex.displayName')}}</label>
              <div class="form-view-row-content">
                {{ genGender() }}
              </div>
            </div>
            <div class="form-view-row">
              <label>{{$t('common.fields.weChatId2.displayName')}}</label>
              <div class="form-view-row-content">
                {{
                  imConversationInfo.weChatId ? imConversationInfo.weChatId : ''
                }}
              </div>
            </div>

            <div class="form-view-row">
              <label>{{$t('common.fields.imSource.displayName')}}</label>
              <div class="form-view-row-content">
                {{ sessionSource }}
              </div>
            </div>

            <template>
              <div class="form-view-row">
                <label>{{$t('common.fields.customerServiceNumber.displayName')}}</label>
                <div class="form-view-row-content">
                  {{ imConversationInfo.customerServiceNumber }}
                </div>
              </div>
            </template>
            <template>
              <div class="form-view-row">
                <label>{{$t('common.fields.customerServiceName.displayName')}}</label>
                <div class="form-view-row-content">
                  {{ imConversationInfo.customerServiceName }}
                </div>
              </div>
            </template>
            <template>
              <div class="form-view-row">
                <label>{{$t('common.fields.relationUserId.displayName')}}</label>
                <div class="form-view-row-content">
                <span class="user-card-triggle" v-user="imConversationInfo.relationUserId">
                  <template v-if="isOpenData" >
                    <open-data
                        type="userName"
                        :openid="imConversationInfo.relationUserStaffId"
                    ></open-data>
                  </template>
                  <template v-else>
                    {{ imConversationInfo.relationUserName }}
                  </template>
                </span>
                </div>
              </div>
            </template>
            <template>
              <div class="form-view-row">
                <label>{{$t('common.fields.touristNo.displayName')}}</label>
                <div class="form-view-row-content">
                  {{ imConversationInfo.touristNo }}
                </div>
              </div>
            </template>
            <template>
              <div class="form-view-row">
                <label>{{$t('common.fields.imStartTime.displayName')}}</label>
                <div class="form-view-row-content">
                  {{ imConversationInfo.startTime | formatDate }}
                </div>
              </div>
            </template>
            <template>
              <div class="form-view-row">
                <label>{{$t('common.fields.imCloseTime.displayName')}}</label>
                <div class="form-view-row-content">
                  {{ imConversationInfo.closeTime | formatDate }}
                </div>
              </div>
            </template>
            <template>
              <div class="form-view-row">
                <label>{{$t('common.fields.imPutChannelId.displayName')}}</label>
                <div class="form-view-row-content">
                  {{
                    imConversationInfo.putChannelName
                        ? imConversationInfo.putChannelName.join(',')
                        : ''
                  }}
                </div>
              </div>
            </template>
            <template>
              <div class="form-view-row">
                <label>{{$t('common.fields.conversationStatus.displayName')}}</label>
                <div class="form-view-row-content">
                  {{
                    [$t('common.fields.conversationStatus.datasource.text1'), $t('common.fields.conversationStatus.datasource.text2'), $t('common.fields.conversationStatus.datasource.text3'),$t('common.fields.conversationStatus.datasource.text4')][
                        imConversationInfo.conversationStatus
                        ]
                  }}
                </div>
              </div>
            </template>
            <template>
              <div class="form-view-row">
                <label>{{$t('common.fields.eventContact.displayName')}}</label>
                <div class="form-view-row-content">
                  <div
                      class="OpenLink"
                      @click="OpenEvent(item)"
                      v-for="item in bizRelInfo"
                      :key="item.id"
                  >
                    {{ item.bizNo }}
                  </div>
                </div>
              </div>
            </template>
            <template>
              <div class="form-view-row">
                <label>{{$t('common.fields.relationProduct.displayName')}}</label>
                <div class="form-view-row-content">
                  <div
                      class="OpenLink"
                      @click="toProductDetail(item.bizId)"
                      v-for="item in imConversationInfo.bizProductInfo"
                      :key="item.id"
                  >{{ item.bizNo }}
                  </div>
                </div>
              </div>
            </template>
            <!-- 纯客服云版本隐藏关联工单 -->
            <template v-if="_isShowTaskModule">
              <div class="form-view-row">
                <label>{{$t('common.fields.relationTask.displayName')}}</label>
                <div class="form-view-row-content">
                  <div
                      class="OpenLink"
                      @click="goTaskDetail(item.bizId, item.bizNo)"
                      v-for="item in imConversationInfo.bizTaskInfo"
                      :key="item.id"
                  >{{ item.bizNo }}
                  </div>
                </div>
              </div>
            </template>
            <div class="form-view-row">
              <label>{{ $t('common.fields.isTimeOut.displayName') }}</label>
              <div class="form-view-row-content">
                {{ imConversationInfo.isTimeOut ? $t('common.base.yes') : $t('common.base.no') }}
              </div>
            </div>
          </div>
        </div>
      </template>
      <template slot="right">
        <div class="im-detail chat-msg" v-show="collapseDirection !== 'right'">
          <el-tabs v-model="rightActiveTab" @tab-click="handleSwitchTab">
            <el-tab-pane :label="$t('common.tabs.im.recordList')" name="1"> </el-tab-pane>
            <el-tab-pane :label="$t('common.tabs.im.tabs1')" name="2"> </el-tab-pane>
            <el-tab-pane :label="$t('common.tabs.im.tabs2')" name="3"> </el-tab-pane>
            <el-tab-pane v-if="satisfactionGray" :label="$t('common.tabs.im.tabs3')" name="4"> </el-tab-pane>
          </el-tabs>
          <div v-show="rightActiveTab === '1'" class="messagebox-content">
            <div v-if="recordList && recordList.length > 0">
              <base-timeline
                  :data="recordList"
                  :record-render="renderRecord"
                  :loading="recordLoading"
                  @load="loadmore"
              />
            </div>
            <div v-else class="default">
              <no-data-view-new></no-data-view-new>
            </div>
          </div>
          <div
              v-show="rightActiveTab === '2'"
              class="messagebox-content"
              ref="msgContent"
          >
            <!-- 聊天记录 -->
            <chattingRecords
                :msg-list="imMessageInfoList"
                :is-show-more="showMore"
                :source="source"
                @loadMoreMsgs="loadMoreMsgs"
                ref="msgContent"
                :user-detail="userDetail"
                :conversation-number="imConversationInfo.conversationNumber"
            />
          </div>
          <div v-show="rightActiveTab==='3'" class="messagebox-content">
            <ServiceNotes ref="ServiceNotes" @refresh="GetInitData" :customer-id="customerId" :is-conversation="true" :conversation-status="imConversationInfo.conversationStatus" :im-setting-config="ImSettingConfig" :id="imId" @RequiredNotes="value => RequiredNotes=value" :biz-no="imConversationInfo.conversationNumber" module="会话详情" />
          </div>
          <div v-show="rightActiveTab==='4'" class="messagebox-content">
            <iframe v-if="satisfactionGray && imConversationInfo.evaluated === 1" id="imIframe" :src="iframeUrl" height="98%" width="100%"/>
            <div v-else class="default">
              <no-data-view-new :notice-msg="$t('im.detail.tips1')"></no-data-view-new>
            </div>
          </div>
        </div>
        <div class="im-title" v-show="collapseDirection === 'right'">
          {{ $t('common.tabs.im.recordList') }}
        </div>
      </template>
    </base-collapse>
    <!-- end 会话信息折叠面板 -->
    <!-- 添加到现有客户的对话框 -->
    <el-dialog
      :title="$t('im.detail.title2')"
      :visible.sync="saveDialogVisible"
      width="420px"
      @close="saveDialogClosed"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="saveForm"
        :rules="saveFormRules"
        ref="saveFormRef"

        label-position="top"
      >
        <el-form-item :label="$t('common.base.customer')" prop="customer">
          <customer-select
            style="line-height: initial;"
            v-model="customer"
            :field="customerField"
            :remote-method="searchCustomer"
            :update-customer="updateCustomer"
            :placeholder="$t('common.placeholder.selectSomething', {0:$t('common.base.customer')})"
          ></customer-select>
        </el-form-item>

        <el-form-item :label="$t('im.detail.label1')" prop="type">
          <el-radio v-model="saveForm.type" :label="0">{{$t('im.detail.label2')}}</el-radio>
          <el-radio v-model="saveForm.type" :label="1">{{$t('im.detail.label3')}}</el-radio>
        </el-form-item>

        <template>
          <el-form-item v-if="saveForm.type==0" :label="$t('common.base.contact')" prop="name">
            <el-input
              v-model="saveForm.name"
              :placeholder="$t('common.placeholder.inputSomething', {data1:$t('common.base.contact')})"
            ></el-input>
          </el-form-item>

          <el-form-item v-if="saveForm.type==1" :label="$t('common.base.contact')" prop="linkman">
            <biz-remote-select
              ref="linkman"
              :placeholder="$t('im.detail.pla2')"
              :cleared="true"
              v-model="saveForm.linkman"
              :remote-method="searchLinkman"
            >
            </biz-remote-select>
          </el-form-item>
        </template>

        <template>
          <el-form-item v-if="saveForm.email" :label="$t('common.fields.email.displayName')" prop="email">
            <!-- weChat可修改 -->
            <el-input
              v-model="saveForm.email"
              :disabled="source !== 'weChat'"
            ></el-input>
          </el-form-item>
          <el-form-item v-else :label="$t('common.fields.contactNumber.displayName')" prop="phone">
            <!-- weChat可修改 -->
            <el-input
              v-model="saveForm.phone"
              :disabled="source !== 'weChat'"
            ></el-input>
          </el-form-item>
        </template>

      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="saveDialogVisible = false">{{$t('common.base.cancel')}}</el-button>
        <el-button type="primary" @click="saveUserClick"
        >{{$t('common.base.confirm')}}</el-button
        >
      </span>
    </el-dialog>
    <!-- 会话转交 -->
    <SessionTransferDialog :conversationId="imId" ref="SessionTransferDialog" pageFrom="imDetail" @SaveCallBack="SaveForwarding" />
  </div>
</template>

<script>

import { isOpenData, openAccurateTab } from '@src/util/platform';
import * as IMApi from '@src/api/ImApi.js';
import { parse } from '@src/util/querystring';
import { formatDate } from 'pub-bbx-utils';
import { isOnlyCustomerServiceCloudVersion } from '@src/util/version.ts';
import ChatMixin from '../ChatMixin';
import BenzAMRRecorder from 'benz-amr-recorder';
import NewConstructionByIM from '@src/modules/im/components/NewConstructionByIM.vue'
import ServiceNotes from './ServiceNotes';
import AssociatedEvents from '../imChat/components/chatDetail/AssociatedEvents';
import chattingRecords from '../imChat/components/messageBox/chattingRecords/index.vue'
import { getRootWindow } from '@src/util/dom'
import { mapActions } from 'vuex'
import { safeNewDate } from '@src/util/time';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import NoDataViewNew from '@src/component/common/NoDataViewNew';
import i18n from '@src/locales'
import SessionTransferDialog from '@src/modules/im/components/SessionTransferDialog.vue'
import platform from '@src/platform';
/* mixin */
import { VersionControlTaskMixin, VersionControlOtherMixin } from '@src/mixins/versionControlMixin';
import { SessionSourceMap } from '@model/enum/ImEnum.js'
const registerTypeMaps = {
  2: i18n.t('common.fields.imRegisterType.dataSource.text1'),
  3: i18n.t('common.fields.imRegisterType.dataSource.text2'),
  4: i18n.t('common.fields.imRegisterType.dataSource.text3')
}

export default {
  mixins: [
    ChatMixin,
    VersionControlTaskMixin,
    VersionControlOtherMixin
  ],
  name:'imDetail',
  data() {
    return {
      isOpenData,
      imConversationInfo: {},
      bizRelInfo: [],
      imMessageInfoList: [],
      total: null,
      showMore: false,
      clickMore: false,
      loading: true,
      customerId: '',
      rightActiveTab: '1',
      recordList: [],
      recordLoading: false,
      ForwardingItem: {},
      RequiredNotes: false,
      ImSettingConfig: {},
      operationalData:{},
      iframeUrl:'',
      registerTypeMaps,
      showCollapse: true,
      collapseDirection: '',
    };
  },
  computed: {
    customerName() {
      return this.imConversationInfo?.customerName;
    },
    source() {
      return this.imConversationInfo?.source;
    },
    isWeChat() {
      return this.imConversationInfo?.source == 'weChat';
    },
    satisfactionGray() {
      const RootWindow = getRootWindow(window);
      return RootWindow.grayAuth?.satisfaction || false;
    },
    userDetail(){
      return {...this.imConversationInfo }
    },
    isTourist() {
      return this.userDetail?.registerType === 4;
    },
    sessionSource() {
      return SessionSourceMap[this.source] || ''
    },
  },
  filters: {
    formatDate(value) {
      return formatDate(value, 'YYYY-MM-DD HH:mm:ss');
    },
    InitializationTime(value) {
      if (typeof value === 'string') {
        let time = value.slice(0, 19);
        return (
          safeNewDate(time).getTime()
          + safeNewDate().getTimezoneOffset() * 60 * 1000 * -1
        );
      }
      return value;

    },
  },
  updated() {
    // this.scollBottom();
  },
  created() {
    this.GetInitData();
    // 新建工单，新建事件权限以及模板列表
    this.get_operationalData()
    // 新建pass模板列表
    this.get_operationalDataByPass()
    this.iframeUrl = `/pcoperation/task/evaluate?id=${this.imId}&fromIM=true`
  },
  methods: {
    ...mapActions(['get_operationalData', 'get_operationalDataByPass']),
    async getTenantImSetting() {
      try {
        const { code, data = {} } = await IMApi.getTenantImSetting();
        if (code !== 0) return;
        this.ImSettingConfig = data.config;
      } catch (error) {
        console.error('error', error);
      }
    },
    OpenEvent(item) {
      // this.$platform.openTab({
      //   id: `event_view_${item.bizId}`,
      //   title: `事件${item.bizNo}`,
      //   close: true,
      //   url: `/event/view/${item.bizId}`,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageEventView,
        key: item.bizId,
        titleKey: item.bizNo
      })
    },
    saveBizRel() {
      this.GetInitData();
    },
    GetInitData() {
      const query = parse(window.location.search) || {};
      this.imId = query.id;
      let parmas = {
        id: this.imId,
        pageNum: 1,
        pageSize: 10,
        type:1
      };
      this.getConversationInfo(parmas);
      this.queryChatRecord(parmas);
      this.getDynamicContent();
      this.getTenantImSetting();
      this.getOperationalData()
    },
    TransferToLabor() {
      IMApi.transferToLabor({
        conversationId: this.imId,
      }).then(res => {
        if (res.code === 0) {
          this.$message({
            message: this.$t('im.detail.tips4'),
            type: 'success',
          });
          // 重新刷新数据
          this.GetInitData();
        } else {
          this.$message.error(res.message);
        }
      });
    },
    EndSession() {
      // RequiredNotes为true无数据且服务备注为必填项
      if (this.RequiredNotes) {
        // 服务备注在编辑状态，提示并切换至服务备注
        this.$confirm(this.$t('im.detail.tips5'), this.$t('common.base.toast'), {
          confirmButtonText: this.$t('common.base.confirm'),
          cancelButtonText: this.$t('common.base.cancel'),
          closeOnClickModal:false,
          type: 'warning'
        }).then(() => {
          this.rightActiveTab = '3'
          this.$refs.ServiceNotes.Amendment = true;
        }).catch(() => { });
      }else{
        this.finished()
      }
    },
    finished() {
      this.$confirm(this.$t('im.detail.tips6'), this.$t('common.base.toast'), {
        confirmButtonText: this.$t('common.base.confirm'),
        cancelButtonText: this.$t('common.base.cancel'),
        closeOnClickModal: false,
        type: 'warning',
      })
        .then(() => {
          IMApi.finished({
            conversationId: this.imId,
          }).then(res => {
            if (res.code === 0) {
              this.$message({
                message: this.$t('im.detail.btn3'),
                type: 'success',
              });
              // 重新刷新数据
              this.GetInitData();
            } else {
              this.$message.error(res.message);
            }
          });
        })
        .catch(() => {});
    },
    play(item, id) {
      const { filename, url } = item;
      if (this.judgedFileType(filename) != 'audio.png') return;
      let amr = new BenzAMRRecorder();
      let ele = document.querySelector(`.voice_${id}`);
      amr.initWithUrl(url).then(() => {
        // amr.isPlaying() 返回音频的播放状态 是否正在播放 返回boolean类型
        if (amr.isPlaying()) {
          amr.stop();
          ele.style.display = 'none';
        } else {
          amr.play();
          ele.style.display = 'block';
        }
      });
      amr.onEnded(() => {
        ele.style.display = 'none';
      });
    },
    openCustomer(id) {
      let fromId = window.frameElement.getAttribute('id');
      // this.$platform.openTab({
      //   id: `customer_view_${id}`,
      //   title: '客户详情',
      //   close: true,
      //   url: `/customer/view/${id}?noHistory=1`,
      //   fromId,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageCustomerView,
        key: id,
        params: 'noHistory=1',
        fromId
      })
    },
    scollBottom() {
      setTimeout(() => {
        const dom = this.$refs.msgContent;
        if (!dom) return;
        dom.scrollTop = dom.scrollHeight;
      }, 0);
    },
    loadMoreMsgs() {
      this.showMore = false;
      this.clickMore = true;
      let params = {
        id: this.imId,
        pageNum: 1,
        pageSize: this.total,
        type:1
      };
      this.getConversationInfo(params);
      this.queryChatRecord(params);
    },
    getConversationInfo(parmas) {
      let loadingMore;
      if (this.clickMore) {
        loadingMore = this.$loading({
          target: document.querySelector('.messagebox-content'),
          text: this.$t('common.base.loading'),
        });
      }
      IMApi.getConversationInfo(parmas)
        .then(res => {
          this.loading = false;
          if (res.code == 0) {
            this.customerId = res.data.baseCustomerId;
            res.data.customerId = res.data.baseCustomerId
            res.data.conversationNo = res.data.conversationNumber
            this.imConversationInfo = res.data;
            this.bizRelInfo = res.data.bizRelInfo;
            loadingMore?.close();
            this.setPageTitle(res.data)
          }
        })
        .catch(err => {
          console.error(err);
          this.loading = false;
          loadingMore && loadingMore.close();
        });
    },
    getDynamicContent() {
      IMApi.getDynamicContent({ conversationId: this.imId }).then(res => {
        if (res.code == 0) {
          res.data?.map(v=>{
            v.createTime = v.eventTime
          })
          this.recordList = res.data;
        }
      });
    },
    handleDelete() {
      this.$confirm(this.$t('im.list.tips2'), this.$t('common.base.toast'), {
        confirmButtonText: this.$t('common.base.confirm'),
        cancelButtonText: this.$t('common.base.cancel'),
        type: 'warning',
      })
        .then(async () => {
          let selectedIds = [];
          selectedIds.push(this.imId);
          const { code } = await IMApi.removeConversations(selectedIds);
          if (code == 0) {
            let fromId = window.frameElement.getAttribute('fromid');
            this.$platform.refreshTab(fromId);
            let id = window.frameElement.dataset.id;
            setTimeout(() => {
              this.$platform.closeTab(id);
            }, 500);
          }
        })
        .catch(() => {});
    },
    /**
     * @description 加载下一页
     */
    async loadmore() {
      try {
        this.params.pageNum++;
        this.recordLoading = true;

        // let data = await this.fetchRecord(this.params);

        this.recordLoading = false;
        this.recordPage.merge(data.result);
      } catch (error) {
        console.warn('loadmore -> error', error);
      }
    },
    renderRecord(h, record) {
      const { eventSponsor, eventContent, eventTime, eventSponsorUserId, eventTargetName, eventTargetUserId, eventSponsorStaffId } = record;
      let InitializationTime = value => {
        if (typeof value === 'string') {
          let time = value.slice(0, 19);
          // safeNewDate().getTimezoneOffset() 获取的是当前时区 小时 乘 60 分钟的值
          return (
            safeNewDate(time).getTime()
            + safeNewDate().getTimezoneOffset() * 60 * 1000 * -1
          );
        }
        return value;

      };
      return (
        <div>
          <div>
            {this.renderUserName(eventSponsor,eventSponsorStaffId,eventSponsorUserId)}
            {eventContent}{eventTargetName}
          </div>
        </div>
      );
    },
    renderUserName(userName, staffId, userId){
      if(userId){
        if(isOpenData && staffId) return <strong class="user-card-triggle" v-user={userId}>{<open-data type="userName" openid={staffId}></open-data>}</strong>
        return <strong class="user-card-triggle" v-user={userId}>{userName}</strong>
      }
      if(isOpenData && staffId) return <strong>{<open-data type="userName" openid={staffId}></open-data>}</strong>
      return <strong>{userName}</strong>
    },
    SessionForwarding() {
      this.$refs.SessionTransferDialog.open()
    },
    // 会话转交——提交
    SaveForwarding(){
      setTimeout(() => {
        const fromId = window.frameElement.getAttribute('id');
        this.$platform.refreshTab(fromId);
      }, 2000);
    },
    // 查询聊天记录
    async queryChatRecord(parmas) {
      parmas.conversationId = parmas.id;
      const { code, data } = await IMApi.queryChatRecord(parmas);
      this.imMessageInfoList = data.list;
      this.total = data.total;
      this.showMore = this.total > 10;
      if (this.clickMore) {
        this.showMore = false;
        this.clickMore = false;
        this.$nextTick(() => {
          const id = this.imMessageInfoList[this.imMessageInfoList.length - 10]
            .id;
          let ele = document.querySelector(`.item-${id}`);
          let pele = document.querySelector('.messagebox-content');
          pele.scrollTop = ele.offsetTop - ele.offsetHeight / 2;
        });
      } else {
        this.scollBottom();
      }
    },
    // 跳转到产品详情
    toProductDetail(productId){
      let fromId = window.frameElement.getAttribute('id');
      // this.$platform.openTab({
      //   id: `product_view_${productId}`,
      //   title: '产品详情',
      //   close: true,
      //   url: `/customer/product/view/${productId}?noHistory=1`,
      //   fromId,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageProductView,
        key: productId,
        params: 'noHistory=1',
        fromId
      })
    },
    // 跳转到工单详情
    goTaskDetail(id, taskNo){
      let fromId = window.frameElement.getAttribute('id')
      // this.$platform.openTab({
      //   id: `task_view_${id}`,
      //   title: `工单${taskNo}`,
      //   close: true,
      //   url: `/task/view/${id}`,
      //   fromId
      // })
      openAccurateTab({
        type: PageRoutesTypeEnum.PageTaskView,
        key: id,
        titleKey: taskNo,
        fromId
      })
    },
    async getOperationalData(){
      const { status, data } = await IMApi.getOperationalData()
      if (status === 0) {
        this.operationalData = data
      }
    },
    async saveUserClick(){
      await this.saveUser(this.imId)
      this.GetInitData()

    },

    handleSwitchTab(tab) {
      this.$track.clickStat(this.$track.formatParams('DETAIL_ADD_ONS_TABS', tab.label))
    },

    getBtnsTrackData(id, data) {
			return this.$track.formatParams(id, data, 'DETAIL_BTNS_GROUP')
		},
    toSaveLinkmansave(...rest) {
      this.saveLinkman(...rest)
      this.$track.clickStat(this.getBtnsTrackData('CREATE_LINKMAN'))
    },
    setPageTitle(data) {
      if (window.frameElement) {
        let title = i18n.t('common.pageTitle.pageImView')
        if(this.$route.query.id){
          title += data.conversationNo
        }
        const currentTabId = window.frameElement.dataset.id;
        platform.setTabTitle({
          id: currentTabId,
          title
        })
      }
    },
    genGender() {
      if(this.imConversationInfo.source == 'weChat') return i18n.t('common.base.unknown')
      const sexMap = {
        0: i18n.t('common.base.woman'),
        1: i18n.t('common.base.man')
      }
      return sexMap[this.imConversationInfo.gender]
    }
  },
  components: {
    ServiceNotes,
    AssociatedEvents,
    chattingRecords,
    NewConstructionByIM,
    NoDataViewNew,
    SessionTransferDialog,
  },
};
</script>

<style lang="scss" scoped>
::v-deep .base-timeline-content strong {
  word-break:break-all;
}
::v-deep .el-tabs {
  height: auto;
}
::v-deep .el-button {
  margin-left: 12px;
}
.add-action {
  display: flex;
}
::v-deep .el-button {
  margin-left: 12px;
}
::v-deep .el-button--danger:hover {
  background: #ff7875;
  border-color: #ff7875;
  color: #ffffff;
}
::v-deep .el-button--danger:focus{
  background: #FF7875;
  border-color: #FF7875;
  color: #ffffff;
}
.OpenLink{
  color:$color-primary-light-6 ;
  cursor: pointer;
  display: inline-block;
  margin-right: 10px;
}
.OpenLink:hover {
  text-decoration: underline;
}

::v-deep .el-tabs__item {
  padding: 0 24px !important;
}
::v-deep .el-tabs__header {
  margin: 0;
  line-height: 48px;
  height: 48px;
  background: #fafafa;
  border-radius: 4px 4px 0px 0px;
}
html,
body,
.detail {
  height: 100%;
  overflow-y: hidden;
  box-sizing: border-box;
  padding-bottom: 12px;
}
.detail {
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  .detail-header {
    background: #fff;
    padding: 14px 16px 14px 16px;
    margin: 12px;
    border-radius: 4px;
    box-shadow: 0px 2px 8px 0px rgba(0, 0, 0, 0.1);
    display: flex;
    justify-content: space-between;
  }
  .btn-bg {
    background: #f5f8fa;
  }
  .im-title {
    padding-left: 20px;
    line-height: 48px;
    height: 48px;
    background: #fafafa;
    border-radius: 4px 4px 0 0;
  }
  .other-title {
    color: $color-primary-light-6;
  }
  .detail-main-content {
    padding: 0 12px;
    .customer-name {
      color: $color-primary;
      cursor: pointer;
    }
    .im-detail {
      background: #fff;
      height: 100%;
      overflow: hidden;
      padding-bottom: 10px;
      .im-content {
        height: calc(100vh - 98px);
        overflow: auto;
      }
      .form-container {
        // height: 100%;
        height: calc(100% - 48px);
        overflow-y: auto;
      }
    }
  }
  .form-view-row label {
    width: 120px !important;
  }
  .messagebox-content {
    overflow-y: auto;
    // height: 470px;
    height: calc(100vh - 150px);
    padding: 10px;
    .iconfont-wrap {
      font-size: 12px;
      color: #262626;
      i {
        color: $color-primary-light-6;
      }
      height: 30px;
      text-align: center;
      line-height: 30px;
    }
    .chat-content {
      padding-top: 20px;
      img {
        width: 36px;
        height: 36px;
      }
      font-size: 14px;
      .info {
        display: flex;
        .info-content {
          max-width: 300px;
          margin-left: 8px;
          padding: 8px 12px;
          border: 1px solid #eee;
          border-radius: 0 8px 8px 8px;
          word-wrap: break-word;
          color: #595959;
        }
      }
      .info-time {
        margin-left: 44px;
        font-size: 12px;
        margin-top: 5px;
        color: #bfbfbf;
      }
      .info-status {
        align-self: flex-end;
        font-size: 12px;
        color: #bfbfbf;
        margin-left: 4px;
      }
      .word-my {
        .info {
          display: flex;
          justify-content: flex-end;
          .info-status {
            margin-right: 4px;
          }
          .info-content {
            margin: 0 8px 0 0;
            background: $color-primary-light-1;
            border: 1px solid rgba(0, 209, 178, 0.32);
            border-radius: 8px 0 8px 8px;
            color: #595959;
          }
        }
        .info-time {
          text-align: right;
          margin-right: 44px;
        }
      }
      .msg-img {
        width: 90px;
        height: 120px;
        margin-right: 10px;
        object-fit: contain;
      }
      .file-content {
        display: flex;
        max-width: 80%;
        padding: 10px;
        .file-img {
          width: 40px;
          height: 40px;
          margin-right: 10px;
        }
        p {
          margin-bottom: 4px;
        }
        a {
          color: $color-primary-light-6 !important;
        }
      }
    }
  }
  .info-imageCode {
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  .info-text {
    width: 100%;
    text-align: center;
  }
  .info-image {
    width: 120px !important;
    height: 120px !important;
    margin: 13px 0;
  }
}
}
</style>
<style lang="scss">
.info-content {
  a {
    color: $color-primary-light-6 !important;
  }
}

.voice {
  display: none;
  height: 35px;
  width: 35px;
  background: #f5f5f5;
  margin-left: 10px;
}

.voice_bg {
  background: url()
    right 0 no-repeat;
  width: 30px;
  height: 30px;
  background-size: 400%;
}

.voice_play {
  animation-name: voicePlay;
  animation-duration: 1s;
  animation-direction: normal;
  animation-iteration-count: infinite;
  animation-timing-function: steps(3);
}

@keyframes voicePlay {
  0% {
    background-position: 0;
  }
  100% {
    background-position: 100%;
  }
}
.ForwardingTitle {
  font-size: 14px;
  font-weight: 400;
  color: #f6a136;
  line-height: 20px;
  margin-top: 10px;
  padding-left: 33px;
  position: relative;
  span {
    position: absolute;
    left: 0;
    color: #595959;
  }
}
</style>
